package com.nidu.demo.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.nidu.demo.common.constants.WebFilterOrder;
import com.nidu.demo.tenant.ability.TenantDomainService;
import com.nidu.demo.tenant.aop.TenantIgnoreAspect;
import com.nidu.demo.tenant.filter.TenantContextWebFilter;
import com.nidu.demo.tenant.filter.TenantSecurityWebFilter;
import com.nidu.demo.tenant.handler.MybatisTenantLineHandler;
import com.nidu.demo.web.config.WebProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(TenantProperties.class)
public class TenantAutoConfiguration {

    @Bean
    public TenantLineInnerInterceptor tenantLineInnerInterceptor(TenantProperties properties) {
        MybatisTenantLineHandler tenantLineHandler = new MybatisTenantLineHandler(properties);
        return new TenantLineInnerInterceptor(tenantLineHandler);
    }

    @Bean
    public FilterRegistrationBean<TenantContextWebFilter> tenantContextWebFilter() {
        FilterRegistrationBean<TenantContextWebFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TenantContextWebFilter());
        registrationBean.setOrder(WebFilterOrder.TENANT_CONTEXT_FILTER);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<TenantSecurityWebFilter> tenantSecurityWebFilter(TenantProperties tenantProperties, WebProperties webProperties,
                                                                                   TenantDomainService tenantDomainService) {
        FilterRegistrationBean<TenantSecurityWebFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TenantSecurityWebFilter(tenantProperties, webProperties, tenantDomainService));
        registrationBean.setOrder(WebFilterOrder.TENANT_SECURITY_FILTER);
        return registrationBean;
    }

    @Bean
    public TenantIgnoreAspect tenantIgnoreAspect() {
        return new TenantIgnoreAspect();
    }
}
